<?php (defined('BASEPATH')) OR exit('No direct script access allowed');

class Dependent_Model extends CI_Model {
	
	private $table= 'dependents';
	function __construct() {
		parent::__construct();
		$this->userModel = $this->load->model('User_Model');
		$this->clientModel = $this->load->model('Client_Model');
	}
	
	
	function save($data){
		$this->db->insert($this->table, $data);
		return $this->db->insert_id();
	}
	
	function isExist($array){
		$query = $this->db->get_where($this->table, $array);
    	$result = $query->result();
    	return !empty($result);
	}
	
	function find($array){
		$query = $this->db->get_where($this->table, $array);
    	$result = $query->result();
    	return !empty($result)?$result[0]:false;
	}
	
	function saveOrUpdateData($table, $data){
		$items = $data->dependents;
		$i = 0;

		foreach($items->first_name as $value){
			
			$list = array();
			$list = array('first_name'=>$value,
			'last_name'=> $items->last_name[$i],
			'middle_name' => $items->middle_name[$i],
			'type'=>$items->type[$i],
			'birth_date'=>$items->birth_date[$i],
			'gender'=>$items->gender[$i],
			'user_id'=>$data->user_id);
			
			if($value != "" && $items->last_name[$i] != "" && $items->middle_name[$i] != ""
			&& $items->gender[$i] != "" && $items->gender[$i] != "" ){
				if($this->isExist(array('id' => $items->id[$i]))){
					$this->db->update($table, $list, array('id'=>$items->id[$i]));
				} else {
					$this->db->insert($table, $list);
				}
			}

			$i++;
		}
		return $this->db->insert_id();
	}
	
	function delete($api,$user_id, $id){
		
		$client = $this->clientModel->find($api);
		if(isset($client)){
			$allowed = $this->userModel->isClientAllowed($client->id, $user_id);
			if($allowed) {
				$this->db->where('id', $id);
				$this->db->delete($this->table);
				return true;
			}
		} else {
			return false;
		}
		
	 
	}
}